package rtlmmap

/*
#cgo LDFLAGS: -lftcommap -L../rr/build
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>

void *attachMem( const char *fileName );
void dumpMem( void *h );
void reset( void *h );
void *appData( void *h );
// write point is byte offset of buf
uint64_t writePoint(void *h);
void *getBuf( void *h, uint64_t from, int len);
int tuner(void* h,double ppm,double dftr);
int set_delta(void* h,double dftr);
int set_timing(void* h,double ppm);
*/
import "C"

import (
	"reflect"
	"strconv"
	"unsafe"
)

type CPMem struct {
	handle unsafe.Pointer
	port   int
}

func NewCPMem(p int) *CPMem {
	fn := "rx_rtl." + strconv.Itoa(p)
	cfn := C.CString(fn)
	defer C.free(unsafe.Pointer(cfn))
	return &CPMem{
		handle: unsafe.Pointer(C.attachMem(cfn)),
		port:   p,
	}
}

func (self *CPMem) DumpMem() {
	C.dumpMem(self.handle)
}

func (self *CPMem) GetBuf(from uint64, len int) []byte {
	var buf []byte
	b := (*reflect.SliceHeader)(unsafe.Pointer(&buf))
	b.Cap = len
	b.Len = len
	b.Data = uintptr(unsafe.Pointer(C.getBuf(self.handle, C.uint64_t(from), C.int(len))))
	return buf
}

func (self *CPMem) Tuner(ppm, dftr float64) int {
	return int(C.tuner(self.handle, C.double(ppm), C.double(dftr)))
}
func (self *CPMem) SetDf(dftr float64) {
	C.set_delta(self.handle, C.double(dftr))
}
func (self *CPMem) SetDt(ppm float64) {
	C.set_timing(self.handle, C.double(ppm))
}

func (self *CPMem) WritePoint() uint64 {
	return uint64(C.writePoint(self.handle))
}

func (self *CPMem) GetAppData() unsafe.Pointer {
	return unsafe.Pointer(C.appData(self.handle))
}

func (self *CPMem) Reset() {
	C.reset(self.handle)
}
